#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<errno.h>

typedef void (*func_t)();
#define NUM 5
func_t handlers[NUM];


void Downloed(){
  printf("我是一个下载任务。。。\n");
}

void Log(){
  printf("我是一个记录日志的任务。。。\n");
}

void Flush(){
  printf("我是一个记录日志的任务。。\n");
}

void registerHandler(func_t h[], func_t f){
  int i = 0;
  for(; i < NUM; i++){
    if(h[i] == NULL) break;
  }
  if(i == NUM) return;
  h[i] = f;
}

int main(int argc, char* argv[], char *env[]){
  (void)argc;
  (void)argv;
  (void)env; 
    
  registerHandler(handlers, Downloed);
  registerHandler(handlers, Log);
  registerHandler(handlers, Flush);
  pid_t id = fork();
  if(id == 0) {
    int cnt = 5;
    while(cnt){
      printf("我是一台子进程， pid：%d, ppid: %d\n", getpid(), getppid());
      sleep(1);
      cnt--;
    }
    exit(1);
  }
  while(1){
    int status = 0;
    pid_t rid = waitpid(id, &status, WNOHANG);
    if(rid > 0){
      printf("wait success, rid:%d, exit code:%d, exit signal:%d\n", 
          rid, (status) >> 8 & 0xFF, status & 0x7F);
      break;
    }else if(rid == 0){
      int i = 0;
      for(; handlers[i]; i++){
        handlers[i]();
      }
      printf("本轮调用结束，子进程没有退出\n");
      sleep(1);
    }else{
      printf("等待失败！");
      break;
    }
  }
  return 0;
}
